package com.fanketly.funacg2.ui.viewmodels

import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.model.TagListItem
import com.fanketly.funacg2.data.network.Result
import com.fanketly.funacg2.data.paging.WorkByTagPagingSource
import com.fanketly.funacg2.data.repo.AudioRepo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class TagViewModel @Inject constructor(private val repo: AudioRepo) : ViewModel() {

    private val _tagList = mutableStateOf<List<TagListItem>>(emptyList())
    val tagList: List<TagListItem>
        get() {
            if (_tagList.value.isEmpty()) getTags()
            return _tagList.value
        }
    var tag = 0
    private var source: WorkByTagPagingSource? = null

    val showThisTagPager =
        Pager(
            PagingConfig(
                pageSize = 20, initialLoadSize = 20, enablePlaceholders = true, maxSize = 200
            )
        ) {
//            source ?: WorkByTagPagingSource(0, repo)
            WorkByTagPagingSource(tag, repo)
        }.flow.cachedIn(viewModelScope) // TODO: 2023/8/26   去除了缓存.cachedIn()

    init {
        Log.d(TAG, "TagViewModel_Init: ")
    }

    /**
     * 返回结果false 就不用刷新,true则需要刷新
     * */
    fun setTag(tag: Int): Boolean {
        if (source == null) {
            source = WorkByTagPagingSource(tag, repo)
            return false
        } else if (source!!.tag != tag) {
            source = WorkByTagPagingSource(tag, repo)
            return true
        }
        return false
    }


    fun invalidate() {
        source?.invalidate()
    }

    private fun getTags() {
        viewModelScope.launch {
            repo.getTags().collect {
                when (it) {
                    is Result.Success -> {
                        _tagList.value = it.data
//                        DetailState.Success(it.data, work)
                    }

                    is Result.Error -> {
//                        val message = it.exception?.message ?: ""
//                        if (message.contains("Chain validation failed") || message.contains("401")) DetailState.NotAuthorization
//                        else DetailState.LoadFailed
                        _tagList.value = emptyList()
                    }

                    Result.Loading -> {}
                }
            }
        }
    }
}